import { UI_Layer, RedDot_Key } from '../../config/ui_def'
import { UI_Listen } from '../../config/ui_def'
import taskLun from '../base/taskLun'
import { WX_AD_CONFIG, Sdk_Platform, VIVO_AD_CONFIG, OPPO_AD_CONFIG } from '../../frame/constants';
import util from '../tool/util'
// import gacha from '../tool/gacha'
import numeral from '../base/numeral'
cc.Class({
    extends: cc.Component,

    properties: {
    },
    initInfo() {
        he.voice.playMusic('bgm', 'voice')
        if (!he.pool.getPool('tip')) {
            he.pool.createPool('tip', 3, cc.Prefab, "prefab/tip")
        }
        if (!he.pool.getPool('scrollAd')) {
            he.pool.createPoolSync('scrollAd', 5, cc.Prefab, 'uimod/scrollAd')
        }
        if (!he.pool.getPool('adIcon')) {
            he.pool.createPoolSync('adIcon', 5, cc.Prefab, 'uimod/adIcon')
        }
        if (!he.pool.getPool('adIconSec')) {
            he.pool.createPoolSync('adIconSec', 5, cc.Prefab, 'uimod/adIconSec')
        }
        gg.eventManager.on('main', this.listenClient, this)
        let guideList = he.local.getJson('guideList', 'user')
        if (!guideList) {
            this.guideList = [0, 0, 0, 0, 0, 0, 0]
            he.local.set('guideList', this.guideList, 'user')
            this.isNew = true
            this.updateShop()
            this.addTryUsetInfo()
            he.local.setJson('isNew', this.isNew)
        } else {
            this.guideList = guideList
            this.isNew = he.local.getJson('isNew') || false
            // if (!guideList[3] && !gg.data.isManHua) {
            //     console.log("新手引导未完成第二次进入", guideList)
            //     guideList = [0, 0, 0, 0, 0, 0, 0]
            //     this.guideList = guideList
            //     this.isNew = true
            //     this.updateShop()
            //     this.addTryUsetInfo()
            //     he.local.setJson('isNew', this.isNew)
            // } else {
            // this.adSwitch(true)
            // }
            // he.local.set('guideList', this.guideList, 'user')
        }
        this.adWaitTime = 0
        this.loginTime = 0
        this.chayeTime = 30
        this.bannerTime = 10
        this.videoTime = 30
        this.canShowAd = true
        this.canShowChaye = true
        this.canshowBanner = false
        this.canshowVideo = true
        this.pageInit()
        let dida = he.local.get('local_dida')
        if (!dida) {
            this.dida = 0
        } else {
            this.dida = dida
        }
        this.updateMission()
        this.doubleCheck()
        this.scheduleOnce(() => {
            gg.redManager.updateRedDot()
        }, 0.2)
        if (gg.uiManager.preScene == 'Playground') {
            let localtimeSave = he.local.getJson('localTimeSave')
            if (!localtimeSave) {
                localtimeSave = { loginTime: 0, chayeTime: 30, bannerTime: 10, videoTime: 30 }
            }
            this.loginTime = localtimeSave.loginTime
            this.chayeTime = localtimeSave.chayeTime
            this.bannerTime = localtimeSave.bannerTime
            this.videoTime = localtimeSave.videoTime
            if (guideList[5] && !guideList[6]) {
                let team = he.local.getJson('team', 'user')
                for (let index = 0; index < team.length; index++) {
                    if (team[index].id != 1001) {
                        team.splice(index)
                    }
                }
                he.local.setJson('team', team, 'user')
                gg.eventManager.emit('newGuide', { index: 6 })
            } else {
            }
            switch (common.sdk_env) {
                case Sdk_Platform.OPPO:
                    if (!guideList[6]) {
                        break
                    }
                    gg.uiManager.addPage(UI_Layer.Cover, {
                        name: 'boxPage',
                        cover: true
                    })
                    break
            }
            let sign_histroy = he.local.getJson('sign_histroy', 'user')

            if (sign_histroy && sign_histroy.length && !util.checkCrossDay(sign_histroy[sign_histroy.length - 1])) {
                this.chaYeAd()
                return
            }
        } else {
            this.adSwitch(true)
        }

    },
    onDestroy() {
        this.node.targetOff(this)
        // he.local.setJson('loginTime', this.loginTime)
        let localTimeSave = { loginTime: this.loginTime, chayeTime: this.chayeTime, bannerTime: this.bannerTime, videoTime: this.videoTime }
        he.local.setJson('localTimeSave', localTimeSave)
    },
    runGuide() {
        let guideCtl = this.node.getComponent('guideCtl')
        guideCtl.runTask2(1)
    },
    // 测试
    test() {
        gg.data.goPass(10101)
        cc.director.loadScene("Playground");
    },

    testBigNum() {
        let num = numeral(1101)
        let value = num.format('0,a.00');
        // console.log(value)
    },



    chaYeAd() {
        switch (common.sdk_env) {
            case Sdk_Platform.WECHAT:
                he.ad.interstitialShow()
                break
        }
    },
    adSwitch(status) {
        if (status) {
            switch (common.sdk_env) {
                case Sdk_Platform.WECHAT:
                    if (!common.showAd) return
                    let guideList = he.local.getJson('guideList', 'user')
                    if (!guideList[3]) return
                    // he.ad.getTdAdJson(WX_AD_CONFIG.tmIcon[0], this.uiSet.bind(this))
                    this.newHotAd()
                    break
            }
        } else {
            //  关掉广告
        }
    },
    uiSet(config) {
        if (config.isOpen) {
            gg.uiManager.addPage(UI_Layer.Cover, {
                name: 'adScroll',
                imgList: config.creatives,
                cover: true,
                cover_opacity: 200
            })
        }
    },

    newHotAd() {
        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'hotAdPage',
            cover: true,
            cover_opacity: 200
        })
    },



    //type:0  隐藏page
    listenClient(code, param, arg) {
        if (parseInt(code.type)) {
            switch (parseInt(code.type)) {
                case UI_Listen.MAIN_CLOSEPAGE:
                    this.closePage(code.pageName)
                    this.checkPageName(code.pageName)
                    gg.uiManager.closePage(UI_Layer.Msg, 'chayeAdFake')
                    break
                case UI_Listen.MAIN_TOMAIN:
                    if (code.passId) {
                        this.pageInit(code.passId)
                    }
                    else {
                        this.pageInit(gg.data.pass_id)
                    }
                    gg.uiManager.closePage(UI_Layer.Msg, 'chayeAdFake')
                    this.checkPageName('BottomBar')
                    break
                case UI_Listen.MAIN_SHOWPASS:
                    this.closePage()
                    this.showPass(code.passId)
                    // this.bg.spriteFrame = he.load.get('mainNew', cc.SpriteAtlas, 'plist').getSpriteFrame(`imag_guanqia`)
                    gg.uiManager.addPage(UI_Layer.Cover, {
                        name: 'RightBar',
                    })
                    gg.uiManager.addPage(UI_Layer.Cover, {
                        name: 'LeftBar',
                    })
                    gg.uiManager.addPage(UI_Layer.Cover, {
                        name: 'topBar',
                    })
                    break
                case UI_Listen.MAIN_NEWROLE:
                    gg.eventManager.emit('newGuide', { index: 1 })
                    return
                    break
                case UI_Listen.MAIN_GUIDEEND:
                    this.isNew = false
                    he.local.setJson('isNew', this.isNew)
                    break
                case UI_Listen.MAIN_ENDAD:
                    this.canShowAd = true
                    break
                case UI_Listen.MAIN_NEWPAGE:
                    this.checkPageName(code.pageName)
                    break
                case UI_Listen.MAIN_SHOWVIDEO:
                    // let localTimeSave = { loginTime: this.loginTime, chayeTime: this.chayeTime, bannerTime: this.bannerTime, videoTime: this.videoTime }
                    // he.local.setJson('localTimeSave', localTimeSave)
                    // this.videoTime = 0
                    // this.canShowAd = true
                    if (this.chayeTime >= 10) {
                        gg.uiManager.closePage(UI_Layer.Msg, 'chayeAdFake')
                        if (param) {
                            param()
                            this.chayeTime = 0
                            this.bannerTime = 0
                        }
                    }
                    break
                case UI_Listen.MAIN_CANCLOSEAD:

                    break
            }
        }
    },
    closePage(pageName) {
        gg.uiManager.closePage(UI_Layer.Cover, 'LeftBar')
        gg.uiManager.closePage(UI_Layer.Cover, 'RightBar')
        if (this.openPage) {
            gg.uiManager.closePage(UI_Layer.Cover, this.openPage)
            this.openPage = null
        }
        gg.uiManager.closePage(UI_Layer.Cover, 'topBar')
        gg.uiManager.closePage(UI_Layer.Cover, 'bottomSec')
        // this.bg.spriteFrame = he.load.get('manager', cc.SpriteAtlas, 'plist').getSpriteFrame(`bg_game`)
        if (pageName) {
            this.openPage = pageName
        }
    },
    pageInit(pass) {
        // this.bg.spriteFrame = he.load.get('mainNew', cc.SpriteAtlas, 'plist').getSpriteFrame(`imag_guanqia`)
        if (this.openPage) {
            gg.uiManager.closePage(UI_Layer.Cover, this.openPage)
            this.openPage = null
        }
        if (pass) {
            gg.uiManager.addPage(UI_Layer.Cover, {
                name: 'bottomSec',
                passId: pass
            })
        } else {
            gg.uiManager.addPage(UI_Layer.Cover, {
                name: 'bottomSec',
            })
        }
        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'LeftBar',
        })

        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'RightBar',
        })

        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'BottomBar',
        })

        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'topBar',
        })
        let guideList = he.local.getJson('guideList', 'user')
        // console.log(!guideList[3], gg.data.pass_id == 0)
        if (!guideList[3] && gg.data.pass_id == 0) {
            // console.log(this.isNew, common.comicGuide)
            if (this.isNew && common.comicGuide) {
                gg.uiManager.addPage(UI_Layer.Cover, {
                    name: 'manhuaPage',
                    cover: true,
                    cover_opacity: 240,
                    episode: 0
                })
                he.local.setJson('haveShowComic', true, 'user')
                return
            }
        }
    },
    testServer() {
        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'equipmentPage',
        })
        gg.eventManager.emit('main', { type: 1, pageName: 'equipmentPage' })
    },
    showPass(passId) {
        gg.uiManager.closePage(UI_Layer.Cover, 'bottomSec')
        // console.log('showpass生成的bottomsec')
        gg.uiManager.addPage(UI_Layer.Cover, {
            name: 'bottomSec',
            passId: passId
        })
    },
    //更新更新每日任务
    updateMission() {
        //判断是否跨天
        let last_time_stamp = he.local.get('last_time_stamp', 'user')
        if (util.checkCrossDay(last_time_stamp)) {
            console.log('跨天了')
            let now = new Date().getTime() + this.dida
            he.local.setJson('last_time_stamp', now)
            taskLun.taskInit()
            he.user.saveInfo()
            // this.scheduleOnce(() => {
            //     gg.redManager.updateRedDot(RedDot_Key.TASK, true)
            // }, 0.2)
            this.updateShop()
        } else {
            return
        }
    },
    doubleCheck() {
        let storlist = he.local.getJson('storeList')
        if (storlist && storlist.length > 0) {
        } else {
            this.updateShop()
        }
        let taskList = he.local.getJson('task', 'user')
        if (taskList && taskList.length > 0) {
            // taskLun.taskInit()
        } else {
            taskLun.taskInit()
            // this.scheduleOnce(() => {
            //     gg.redManager.updateRedDot(RedDot_Key.TASK, true)
            // }, 0.2)
        }
        he.user.saveInfo()
    },
    timeCheck() {
        // he.user.saveInfo()
        let now = new Date().getTime() + this.dida
        let now_date = new Date(now)
        // console.log(now_date)
        let hour = now_date.getHours()
        let min = now_date.getMinutes()
        let miao = now_date.getSeconds()
        // console.log(hour)

        if (hour == 0 && min && 0 && miao >= 0 && miao < 10) {
            this.updateMission()
        }
        // this.xstring = `${util.prefixInteger((24 - hour - 1), 2)}:${util.prefixInteger((60 - min - 1), 2)}:${util.prefixInteger((60 - miao), 2)}`
        // console.log(this.xstring)
    },
    updateShop() {
        let shopList = he.db.getTable('Shop')
        this.itemGroup = []
        this.discount = 0.6
        if (shopList && shopList.length > 0) {
            for (let i = 0; i < shopList.length; i++) {
                let itemGrp = shopList[i].monovalent.split('#')
                itemGrp = itemGrp[this.randomNum(0, itemGrp.length - 1)].split('_')
                let itemInfo = he.db.getDataByArgs('Item', { id: parseInt(itemGrp[0]) })
                itemInfo.num = itemGrp[1]
                // itemInfo.sp = parseInt(shopList[i].type) == 1 ? true : false
                if (shopList[i].type == 1) {
                    itemInfo.sp = true
                    let countGrp = shopList[i].preferential.split('#')
                    this.discount = countGrp[this.randomNum(0, countGrp.length - 1)]
                    itemInfo.discount = this.discount
                }
                else {
                    itemInfo.sp = false
                }
                itemInfo.isGet = false
                this.itemGroup.push(itemInfo)
            }
        }
        he.local.setJson('storeList', this.itemGroup)
    },
    //范围内的随机数
    randomNum(minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    },

    checkPageName(pageNaem) {
        this.pageName = pageNaem
        // this.canShowAd = true
        switch (pageNaem) {
            case 'missionPage':
                this.canShowChaye = true
                this.canshowBanner = false
                break
            case 'equipmentPage':
                this.canShowChaye = true
                this.canshowBanner = true
                break
            case 'skillPage':
                this.canShowChaye = true
                this.canshowBanner = false
                break
            case 'bagPage':
                this.canShowChaye = true
                this.canshowBanner = true
                break
            case 'BottomBar':
                this.canShowChaye = true
                this.canshowBanner = false
                break
            case 'signPage':
                this.canShowChaye = false
                this.canshowBanner = true
                break
            case 'rankMainPage':
                this.canShowChaye = true
                this.canshowBanner = false
                break
            case 'storePage':
                this.canShowChaye = false
                this.canshowBanner = false
                break
            case 'equipDetail':
                this.canShowChaye = true
                this.canshowBanner = false
                break
        }
    },
    localConvertWorldPointAR(node) {
        if (node) {
            return node.convertToWorldSpaceAR(cc.v2(0, 0));
        }
        return null;
    },

    update(dt) {
        //控制原生插页或者插页生成的间隔时间30秒
        if (this.chayeTime < 15) {
            this.chayeTime += dt
        }
        //10秒间隔时间为能生成插页和banner的时间，若插页还在cd则生成banner
        if (this.bannerTime < 10) {
            this.bannerTime += dt
        }
        if (this.adWaitTime < 10) {
            this.adWaitTime += dt
        }
        //播放视频的间隔时间60s
        if (this.videoTime < 30) {
            this.videoTime += dt
        }
        //初次进入游戏60秒内不得弹出任何广告
        if (this.loginTime < 5) {
            this.loginTime += dt
        }
        switch (common.sdk_env) {
            case Sdk_Platform.VIVO:
                if (this.canShowAd && this.loginTime >= 5 && !this.isNew && this.chayeTime >= 15 && this.adWaitTime >= 10 && this.canShowChaye) {
                    //生成插页广告
                    // console.log('生成插页')
                    this.canShowAd = false
                    this.chayeTime = 0
                    // this.bannerTime -= 5
                    this.adWaitTime = 0
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'chayeAdFake',
                        isShowAd: true,
                        isShowBanner: false,
                        pageName: this.pageName
                    })
                    // break
                }

                if (this.canShowAd && this.loginTime >= 5 && !this.isNew && this.bannerTime >= 10 && this.adWaitTime >= 10 && this.canshowBanner) {
                    this.bannerTime = 0
                    this.adWaitTime = 0
                    this.canShowAd = false
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'chayeAdFake',
                        isShowAd: true,
                        isShowBanner: true,
                        pageName: this.pageName
                    })
                }
                break
            case Sdk_Platform.OPPO:

                break
        }


    },
    addTryUsetInfo() {
        let team = he.local.getJson('team', 'user')
        for (let index = 0; index < team.length; index++) {
            team.splice(index)
        }
        team.push({
            id: 1001,               // 角色编号
            order: 1,              // 站位排序
            equips: [1, 0, 0, 0],     // 装备等级
            hand: 0,                 // 选择装备
        }, {
            id: 1002,               // 角色编号
            order: -1,              // 站位排序
            equips: [1, 0, 0, 0],     // 装备等级
            hand: 0,                 // 选择装备
        }, {
            id: 1003,               // 角色编号
            order: 2,              // 站位排序
            equips: [1, 0, 0, 0],     // 装备等级
            hand: 0,                 // 选择装备
        }, {
            id: 1004,               // 角色编号
            order: 3,              // 站位排序
            equips: [1, 0, 0, 0],     // 装备等级
            hand: 0,                 // 选择装备
        })
        he.local.setJson('team', team, 'user')
        let cardList = he.local.getJson('card', 'user')
        for (let index = 0; index < cardList.length; index++) {
            cardList.splice(index)
        }
        cardList.push({ id: 3052, lv: 1 })
        cardList.push({ id: 3001, lv: 1 })
        he.local.setJson('card', cardList, 'user')

        let cardTeamList = he.local.getJson('card_team', 'user')
        for (let index = 0; index < cardTeamList.length; index++) {
            cardTeamList.splice(index)
        }
        he.local.setJson('card_team', cardTeamList, 'user')

        let coin = he.local.getJson('coin', 'user')
        coin = parseInt(2000)
        he.local.setJson('coin', coin, 'user')
        let bagList = he.local.getJson('bag', 'user')
        for (let index = 0; index < bagList.length; index++) {
            bagList.splice(index)
        }
        bagList.push(
            { id: 20002, num: 250 },
            { id: 11001, num: 20 },
            { id: 11006, num: 20 },
            { id: 11007, num: 20 },
        )
        he.local.setJson('bag', bagList, 'user')
        let oldUser = he.local.getJson('user')
    }
});
